<?php


namespace app\common\business;


use app\common\lib\SetArray;
use Psr\Log\Test\DummyTest;
use think\Exception;
use think\facade\Cache;

class Cart
{
    /**
     * 添加到redis
     * @param $userId
     * @param $id
     * @param $num
     * @return bool
     */
    public function insertToRedis($userId,  $id, $num) {
        // id获取商品数据
        $goodsSku = (new GoodsSku())->getNormalSkuAndGoods($id);
        if(!$goodsSku) {
            return FALSE;
        }
        $data = [
            "id" => $goodsSku['id'],
            "title" => $goodsSku['goods']['title'],
            "image" => request()->domain() . $goodsSku['goods']['recommend_image'],
            "num" => $num,
            "goods_id" => $goodsSku['goods']['id'],
            "create_time" => time(),
            "stock" => $goodsSku['stock'],
            "selected" => 1
        ];

        try {
            //查询是否已经有该商品
            $get = Cache::hGet(config('redis.cart_pre').$userId, $id);
            if($get) {
                $get = json_decode($get, true);
                $data['num'] = $data['num'] + $get['num'];
            }
            $res = Cache::hSet(config('redis.cart_pre').$userId, $id, json_encode($data));
        } catch (\Exception $e) {
            return FALSE;
        }
        return $res;
    }

    public function lists($userId)
    {
        try {
            $res = Cache::hGetAll(config('redis.cart_pre').$userId);
        } catch (\Exception $e) {
            $res = [];
        }
        if (!$res) {
            return [];
        }
        $result = [];
        $skuIds = array_keys($res);
        //获取sku商品信息
        $skus = (new GoodsSku())->getNormalInIds($skuIds);
        //拆分数据
        $stocks = array_column($skus, "stock", "id");
        $skuIdPrice = array_column($skus, "price", "id");
        $skuIdSpecsValueIds = array_column($skus, "specs_value_ids", "id");
        $specsValues = (new SpecsValue())->dealSpecsValue($skuIdSpecsValueIds);
        //拼接数据
        $totalPrice = 0;
        $selectedCount = 0;
        $checkedAll = true;
        foreach($res as $k => $v) {
            $price = $skuIdPrice[$k] ?? 0;
            $v = json_decode($v, true);
            $v['id'] = $k;
            $v['image'] = preg_match("/http:\/\//", $v['image']) ? $v['image'] : request()->domain().$v['image'];
            $v['price'] = $price;
            $v['total_price'] = $price * $v['num'];
            $v['sku'] = $specsValues[$k] ?? "暂无规则";
            $v['stock'] = $stocks[$k];
            $result[] = $v;
            //选中的商品的总价
            if ($v['selected'] == 1) {
                $totalPrice += $v['total_price'] * 100;
                $selectedCount ++;
            } else {
                $checkedAll = false;
            }
        }
        if(!empty($result)) {
            $result = SetArray::arrsSortByKey($result, "create_time");
        }
        $res = [
            'totalPrice' => sprintf("%.2f", $totalPrice/100),
            'selectedCount' => $selectedCount,
            'checkedAll' => $checkedAll,
            'list' => $result
        ];
        return $res;
    }

    /**
     * 删除/批量删除
     * @param $userId
     * @param $id
     * @return bool
     */
    public function deleteRedis($userId, $ids) {
        if(!is_array($ids)) {
            $ids = explode(",", $ids); // id=1  => [1]  ,  1,2 => [1, 2, 5,6]
        }
        try {
            // ... 是PHP提供一个特性 可变参数
            $res = Cache::hDel(config('redis.cart_pre').$userId, ...$ids);
        }catch (\Exception $e) {
            return FALSE;
        }
        return $res;
    }

    public function getKeys($userId) {
        $hkey = config('redis.cart_pre').$userId;
        $allKeys = array_keys(Cache::hGetAll($hkey));
        return $allKeys;
    }

    /**
     * 更新购物车中的商品数量
     * @param $userId
     * @param $id
     * @param $data
     * @return bool
     * @throws \think\Exception
     */
    public function updateRedis($userId,  $id, $data) {
        try {
            $get = Cache::hGet(config('redis.cart_pre').$userId, $id);
        }catch (\Exception $e) {
            return FALSE;
        }
        if($get) {
            $get = json_decode($get, true);
            if ($get['num'] != $data['num']) {
                $data['selected'] = 1;
            }
            $get['num'] = $data['num'];
            $get['selected'] = $data['selected'];
        } else {
            throw new \think\Exception("不存在该购物车的商品，您更新没有任何意义");
        }
        try {
            $res = Cache::hSet(config('redis.cart_pre').$userId, $id, json_encode($get));
        }catch (\Exception $e) {
            return FALSE;
        }
        return $res;
    }

    /**
     * 获取购物车商品数量
     * @param $userId
     * @return int
     */
    public function getCount($userId) {
        $count = 0;
        try {
            $get = Cache::hGetAll(config('redis.cart_pre').$userId);
            foreach ($get as $v) {
                $v = json_decode($v, true);
                $count += $v['num'];
            }
        }catch (\Exception $e) {
            return $count;
        }
        return intval($count);
    }

    public function changeAll($userId, $status = 1) {
        $keys = $this->getKeys($userId);
        foreach ($keys as $v) {
            try {
                $get = Cache::hGet(config('redis.cart_pre').$userId, $v);
                if($get) {
                    $get = json_decode($get, true);
                    $get['selected'] = $status;
                    Cache::hSet(config('redis.cart_pre').$userId, $v, json_encode($get));
                }
            } catch (\Exception $e) {
                throw new \think\Exception("操作失败");
            }
        }
        return true;
    }

    public function getSlectedList($userId) {
        try {
            $res = Cache::hGetAll(config('redis.cart_pre').$userId);
        } catch (\Exception $e) {
            $res = [];
        }
        if (!$res) {
            return [];
        }
        $result = [];
        $skuIds = [];
        foreach ($res as $k=>$v) {
            $v = json_decode($v, true);
            if ($v['selected'] == 1) {
                $skuIds[] = $k;
            } else {
                unset($res[$k]);
            }
        }
        if (!$res) {
            return [];
        }
        //获取sku商品信息
        $skus = (new GoodsSku())->getNormalInIds($skuIds);
        //拆分数据
        $stocks = array_column($skus, "stock", "id");
        $skuIdPrice = array_column($skus, "price", "id");
        $skuIdSpecsValueIds = array_column($skus, "specs_value_ids", "id");
        $specsValues = (new SpecsValue())->dealSpecsValue($skuIdSpecsValueIds);
        //拼接数据
        $totalPrice = 0;
        foreach($res as $k => $v) {
            $price = $skuIdPrice[$k] ?? 0;
            $v = json_decode($v, true);
            //验证库存
            if ($v['num'] > $stocks[$k]) {
                throw new Exception("{$v['title']} {$specsValues[$k]}: 库存不足");
            }
            $v['id'] = $k;
            $v['image'] = preg_match("/http:\/\//", $v['image']) ? $v['image'] : request()->domain().$v['image'];
            $v['price'] = $price;
            $v['total_price'] = $price * $v['num'];
            $v['sku'] = $specsValues[$k] ?? "暂无规则";
            $result[] = $v;
            //选中的商品的总价
            if ($v['selected'] == 1) {
                $totalPrice += $v['total_price'] * 100;
            }
        }
        if(!empty($result)) {
            $result = SetArray::arrsSortByKey($result, "create_time");
        }
        $res = [
            'totalPrice' => sprintf("%.2f", $totalPrice/100),
            'list' => $result
        ];
        return $res;
    }
}